#ifndef COMMON_H
#define COMMON_H
#include <avr/io.h>

#define MCU_CS		PINB3
#define MCU_LDR		PINB4
#define MCU_MOSI	PINB0
#define MCU_MISO	PINB1
#define MCU_SCK		PINB2

typedef uint8_t		uint8;
typedef uint16_t	uint16;
typedef uint32_t	uint32;
typedef unsigned char byte;
typedef unsigned int		size_t;
typedef unsigned int		time_t;

// This just makes my life easier
//#define BIT16(b) ((unsigned long)0x00000001 << (b))
#define BIT32(b) ((uint32)0x00000001 << (b))
#define BIT16(b) ((uint16)0x0001 << (b))
#define	BIT8(b) (0x01 << (b))

// from AVR035: Efficient C Coding for AVR
#define BSET(ADDRESS,BIT) (ADDRESS |= (unsigned char)(1<<BIT))
#define BCLR(ADDRESS,BIT) (ADDRESS &= (unsigned char)~(1<<BIT))
#define BTOG(ADDRESS,BIT) (ADDRESS ^= (unsigned char)(1<<BIT))
#define BCHK(ADDRESS,BIT) (ADDRESS &  (unsigned char)(1<<BIT))

#define BMSET(x,y) (x |= (y))
#define BMCLR(x,y) (x &= (~y))
#define BMTOG(x,y) (x ^= (y))
#define BMCHK(x,y) (x & (y))

#ifndef Max
#define Max(x,y) ((x)>=(y)?(x):(y))
#endif

#ifndef Min
#define Min(x,y) ((x)<=(y)?(x):(y))
#endif

#ifndef Abs
#define Abs(x) ((x) < 0 ? -(x) : (x))
#endif

#ifndef PI
#define PI 3.1415927
#endif

// C++ Sanity Wrappers
#define nop()                       (asm volatile("nop\n\t"::))
#define BEGIN_CRITICAL_SECTION()    (asm volatile("ldi r16, SREG\n\tcli\n\t"::))
#define END_CRITICAL_SECTION()      (asm volatile("out SREG, r16\n\tsei\n\t"::))
//#define BEGIN_CRITICAL_SECTION()    (volatile uint8 __sregSave = SREG, cli())
//#define END_CRITICAL_SECTION()      (SREG = __sregSave, sei())
#define FNAME()						__PRETTY_FUNCTION__


//////////////////////// [ C++ Safety functions
__extension__ typedef int __guard __attribute__ ((mode (__DI__)));
#ifdef __cplusplus
extern "C" {
#endif
void __cxa_pure_virtual(void);
#if !defined(NO_THREADSAFE_STATICS)
int  __cxa_guard_acquire(__guard *);
void __cxa_guard_release(__guard *);
void __cxa_guard_abort(__guard*);
#endif  /* !NO_THREADSAFE_STATICS */
#ifdef __cplusplus
}
#endif


#if defined(DEFINE_ATEXIT)
void atexit(void) { }	// firmware never exits...
#endif

#if !defined(USE_MEM_MGMT)
// These should be moved into the memory management section when it gets written
void * operator new(size_t size);		// new replacement
void * operator new(size_t, void*);		// placement new
void * operator new[] (size_t size);
void operator delete(void * ptr);
void operator delete(void * p, void * const b);	// placement delete..hmmm
void operator delete[] (void * ptr);
#endif


#endif
